/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.edit.policy;

import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.DirectEditPolicy;
import org.eclipse.gef.requests.DirectEditRequest;
import org.eclipse.uml2.uml.NamedElement;

import com.cea.papyrus.diagram.sequence.sedi.figures.ILabeledFigure;
import com.cea.papyrus.diagram.sequence.sedi.model.command.DirectEditCommand;
import com.cea.papyrus.diagram.sequence.sedi.model.util.ModelUtil;
import com.cea.papyrus.diagraminterchange2.di2.GraphElement;

/**
 * Edit policy to handle direct edit of the name of NamedElements. This policy can be
 * installed on all NamedElement edit parts as well as all edit parts that correspond to
 * NamedElementView model objects.
 * <p>
 * The policy requires the figure to implement ILabeledFigure.
 * </p>
 * 
 * @author frankd@ifi.uio.no
 */
public class LabelDirectEditPolicy extends DirectEditPolicy {

    @Override
    protected Command getDirectEditCommand(DirectEditRequest request) {
        final NamedElement named;
        final Object object = getHost().getModel();
        if (object instanceof NamedElement)
            named = (NamedElement) object;
        else
            named = ModelUtil.<NamedElement> getSemantic(((GraphElement) object));
        String text = (String) request.getCellEditor().getValue();

        DirectEditCommand cmd = new DirectEditCommand(named, text);
        cmd.setLabel("Rename element");
        return cmd;
    }

    @Override
    protected void showCurrentEditValue(DirectEditRequest request) {
        String text = (String) request.getCellEditor().getValue();
        GraphicalEditPart host = (GraphicalEditPart) getHost();
        IFigure figure = host.getFigure();
        ((ILabeledFigure) figure).setLabel(text);
        figure.getUpdateManager().performUpdate();
    }
}
